# -*- coding: utf-8 -*-
# @Date   : 2020/1/19
# @File   : AC06_UnsettledLoanNum_of_Institution_Change_Value.py
# @Author : zhaochen
'''eof
name:未结清贷款机构数_change_value
code:AC06_UnsettledLoanNum_of_Institution_Change_Value
tableName:
columnName:
groups:AC模块
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import json

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def isFloat(x):
    '''
    判断x为float类型且大于等于0
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def getRatingInfoData(code, interface=None, last=False):
    '''
    获取上次评级信息的指标值或接口数据，默认返回的格式是tuple(val, "value") 指标值和标记
    标记分为 'value':指标值 'data':数据
    :param code: 要获取的指标值的指标code
    :param interface: EC_DSJ_2D/IC_DSJ_2D/TX_CQ_DSJ
    :return:
    '''
    try:
        historyRatingInfo = json.loads(ratingRequest.get("historyRatingInfo"))
        if last:
            # 获取上次评级数据信息
            ratingInfo = historyRatingInfo.get("lastRatingInfo")
        else:
            # 获取本次评级数据
            ratingInfo = historyRatingInfo.get("ratingInfo")
        # 如果是取score 或者 ratingLevel 直接返回
        if code in ["score", "ratingLevel"]:
            score = ratingInfo.get(code)
            try:
                return float(score), "value"
            except:
                return None, None
        # 取数据类型进行判断
        dataType = ratingInfo.get("dataType")
        # 如果传回来是数据 则返回相应接口里面的数据data
        if dataType == "1":
            data = ratingInfo.get(interface).get("data")
            if isinstance(data, dict):
                return (data, "data")
            else:
                return None, None
        # 如果传回来是指标值，则通过code进行提取
        elif dataType == "2":
            val = ratingInfo.get(code)
            if val in null_type_list:
                return None, None
            else:
                try:
                    return float(val), "value"
                except:
                    return None, None
        else:
            return None, None
    except:
        return None, None

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)

    if occurTimes == 1:
        if table == "":
            return ""
        if table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        elif len(table) == 0:
            return [{}]
        else:
            return data.get(tableName)

def dateFormat(time):
    try:
        import re
        import datetime
        r1 = re.compile(u'年|月|日')
        time = r1.sub('.', time)
        try:
            date = datetime.datetime.strptime(time, '%Y.%m.%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y-%m-%d')
            except:
                try:
                    date = datetime.datetime.strptime(time, '%Y/%m/%d')
                except:
                    try:
                        r = re.compile(r'\D+')
                        tmp = r.sub('', time)
                        if len(tmp) > 8:
                            tmp = tmp[:8]
                        date = datetime.datetime.strptime(tmp, '%Y%m%d')
                    except:
                        date = None
        return date
    except:
        return None

def UnsettledLoanNumOfInstitution2D(data):
    PCO = getTable(data, 'PCO', 1)
    if PCO is None:
        return u'缺失值'
    elif PCO == [{}] or PCO == "":
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PC02 = getTable(PCO[0], 'PC02', 0)
        if PC02 is None:
            return u'缺失值'
        elif PC02 == [{}] or PC02 == "":
            return 0
        else:
            # 非循环贷账户汇总信息段
            PC02E = getTable(PC02[0], 'PC02E', 0)
            if PC02E is None or PC02E == "":
                f1 = None
            elif PC02E == [{}]:
                f1 = 0
            else:
                PC02ES01 = PC02E[0].get('PC02ES01')
                if PC02ES01 in null_type_list or not isFloat(PC02ES01):
                    f1 = None
                else:
                    f1 = float(PC02ES01)
            # 循环额度下分账户汇总信息段
            PC02F = getTable(PC02[0], 'PC02F', 0)
            if PC02F is None or PC02F == "":
                f2 = None
            elif PC02F == [{}]:
                f2 = 0
            else:
                PC02FS01 = PC02F[0].get('PC02FS01')
                if PC02FS01 in null_type_list or not isFloat(PC02FS01):
                    f2 = None
                else:
                    f2 = float(PC02FS01)
            # 循环贷账户汇总信息段
            PC02G = getTable(PC02[0], 'PC02G', 0)
            if PC02G is None or PC02G == "":
                f3 = None
            elif PC02G == [{}]:
                f3 = 0
            else:
                PC02GS01 = PC02G[0].get('PC02GS01')
                if PC02GS01 in null_type_list or not isFloat(PC02GS01):
                    f3 = None
                else:
                    f3 = float(PC02GS01)
            if f1 is None and f2 is None and f3 is None:
                return u'缺失值'
            else:
                f1 = f1 if f1 is not None else 0
                f2 = f2 if f2 is not None else 0
                f3 = f3 if f3 is not None else 0
                return f1 + f2 + f3

def getTable1d(data, table_Name):
    try:

        data = data.get(table_Name)
        if data in null_type_list:
            return None
        else:
            # 存在1条为空的数据[{}] #ReportNo EC是大写 IC 是reportNo 小写
            if isinstance(data, list) and len(data) == 1 and data[0]['reportNo'] in null_type_list:
                return [{}]
            # 存在表 但为空list []
            elif isinstance(data, list) and len(data) == 0:
                return None
            else:
                return data
    except:
        return None

def UnsettledLoanNumOfInstitution1D(data):
    try:
        ICRUnpaidLoan = getTable1d(data, 'ICRUnpaidLoan')
        if ICRUnpaidLoan is None:
            return None
        elif ICRUnpaidLoan == [{}]:
            return 0
        else:
            financeOrgCount = ICRUnpaidLoan[0].get('financeOrgCount')
            if isFloat(financeOrgCount):
                return float(financeOrgCount)
            else:
                return None
    except:
        return None


def factor1():
    data, data_type = getRatingInfoData('UnsettledLoanNumOfInstitution2D', interface='IC_DSJ_2D', last=False)
    if data_type == 'value':
        try:
            return float(data)
        except:
            return None
    elif data_type == 'data':
        res = UnsettledLoanNumOfInstitution2D(data)
        return res
    else:
        return None

def factor2():
    data, data_type = getRatingInfoData('UnsettledLoanNumOfInstitution1D', interface='IC_DSJ', last=True)
    if data is None:
        # 如果一代的数据没有，则使用二代的数据去取
        data, data_type = getRatingInfoData('UnsettledLoanNumOfInstitution2D', interface='IC_DSJ_2D', last=True)
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = UnsettledLoanNumOfInstitution2D(data)
            return res
        else:
            return None
    else:
        if data_type == 'value':
            try:
                return float(data)
            except:
                return None
        elif data_type == 'data':
            res = UnsettledLoanNumOfInstitution1D(data)
            return res
        else:
            return None

def AC06_UnsettledLoanNum_of_Institution_Change_Value():
    f1 = factor1()
    f2 = factor2()
    if f1 is None or f2 is None or f1 ==u'缺失值' or  f2==u'缺失值':
        return u'缺失值'
    else:
        return f1 - f2

result = AC06_UnsettledLoanNum_of_Institution_Change_Value()